class EventEmitter {
  constructor() {
    this.subs = Object.create(null)
  }
  $on(type, handler) {
    if (this.subs[type]) {
      this.subs[type].push(handler)
    } else {
      this.subs[type] = [handler]
    }
  }
  $emit(type, ...args) {
    if (this.subs[type]) {
      this.subs[type].forEach((handler) => handler(...args))
    }
  }
  $off(type, handler) {
    if (!handler) {
      // 没有传递第二个参数
      delete this.subs[type]
    } else {
      // 传递了第二个参数
      const idx = this.subs[type].findIndex((cb) => cb === handler)
      if (idx) {
        this.subs[type].splice(idx, 1)
        if (this.subs[type].length === 0) {
          delete this.subs[type]
        }
      }
    }
  }
}
